﻿using System;
using System.IO;
using Editor.ProjectDanmaku.EditorWindow;
using ProjectDanmaku.Data;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;

namespace Editor.ProjectDanmaku.Inspector
{
    [CustomEditor(typeof(AvatarInfoAsset))]
    public class AvatarInfoAssetInspector : UnityEditor.Editor
    {
        private bool IsInfoValid(AvatarInfoAsset avatarInfoAsset)
        {
            if (string.IsNullOrEmpty(avatarInfoAsset.avatarName) || string.IsNullOrEmpty(avatarInfoAsset.id))
            {
                return false;
            }

            if (avatarInfoAsset.animatorController == null)
                return false;

            return true;
        }

        private void CreatePrefab(string path, AvatarInfoAsset avatarInfoAsset)
        {
            var root = new GameObject("Avatar_" + avatarInfoAsset.id);
            var container = new GameObject("Avatar");
            container.transform.SetParent(root.transform);

            root.tag = "Player";
            container.tag = "Player";
            
            var animator = container.AddComponent<Animator>();
            animator.runtimeAnimatorController = avatarInfoAsset.animatorController;
            var spriteRenderer = container.AddComponent<SpriteRenderer>();

            foreach (var behvaior in avatarInfoAsset.behaviors)
            {
                if (behvaior.GetClass().IsSubclassOf(typeof(MonoBehaviour)))
                {
                    container.AddComponent(behvaior.GetClass());
                }
            }

            PrefabUtility.SaveAsPrefabAsset(root, path);
            
            DestroyImmediate(root);
        }
        
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            
            var avatarInfoAsset = (AvatarInfoAsset)target;
            var assetPath = AssetDatabase.GetAssetPath(target);
            var dirPath = Path.GetDirectoryName(assetPath);

            if (IsInfoValid(avatarInfoAsset))
            {
                if (GUILayout.Button("创建 Avatar Prefab"))
                {
                    CreatePrefab(Path.Join(dirPath, "Prefab_Avatar.prefab"), avatarInfoAsset);
                }
            }
            else
            {
                GUILayout.Label("信息填写不完整！");
            }
        }
    }
}